<template>
<div :class="[$style.container]">
  <remote-script src="https://g.alicdn.com/dingding/dinglogin/0.0.5/ddLogin.js" id="dingtalk" @load="onLoad" @error="onError"></remote-script>
  <div id="dingtalk_container"></div>
</div>
</template>

<script lang="ts">
import { AppModule } from '@/store'
import { expr } from '@/utils/url'
import { Component, Emit, Prop, Vue } from 'vue-property-decorator'

@Component
export default class DingtalkQrcode extends Vue {
  @Prop({ type: String, default: 'login' }) action!: 'login' | 'bind'

  @AppModule.State properties!: any

  get returnUrl () {
    const url = new URL(location.href)
    // const p = this.action === 'login' ? url.searchParams.get('returnUrl') : url.href
    // return p ? encodeURI(p) : p
    const u = url.protocol + (url.host || '') + (url.pathname || '')
    return encodeURI(u)
  }

  get authorizeUrl () {
    return 'https://oapi.dingtalk.com/connect/oauth2/sns_authorize'
  }

  get appid () {
    return this.properties?.dingTalk?.appKey
  }

  get redirectBaseUrl () {
    return this.properties?.deploy?.externalAccountWeb || expr(this.properties?.deploy?.accountWeb)
  }

  get redirectUrl () {
    const params = `returnUrl=${encodeURIComponent(this.returnUrl || '')}&type=ding_talk&action=${this.action}`
    const path = `${this.redirectBaseUrl}/after-authorize?${params}`
    return path
    // return encodeURIComponent(`${location.origin}/#/after-authorize?returnUrl=${this.returnUrl}&type=ding_talk&action=${this.action}`)
  }

  get goto () {
    const state = 'rawa'
    return encodeURIComponent(`${this.authorizeUrl}?appid=${this.appid}&response_type=code&scope=snsapi_login&state=${state}&redirect_uri=${encodeURIComponent(this.redirectUrl)}`)
  }

  onLoad () {
    const win = window as any
    const ding = win.DDLogin({
      id: 'dingtalk_container',
      goto: this.goto,
      style: 'border:none;background-color:#FFFFFF;',
      width: '300',
      height: '290'
    })
  }

  onError (e: Event) {
    this.$message.error('加载钉钉失败: ' + ((e as any)?.message || ''))
  }

  getCode (loginTmpCode: string) {
    const state = 'rawa'
    const url = `${this.authorizeUrl}?appid=${this.appid}&response_type=code&scope=snsapi_login&state=${state}&redirect_uri=${this.redirectUrl}&loginTmpCode=${loginTmpCode}`
    location.assign(url)
  }

  mounted () {
    const handler = (event: MessageEvent) => {
      const origin = event.origin
      if (origin === 'https://login.dingtalk.com') {
        const loginTmpCode = event.data
        console.log('loginTmpCode', loginTmpCode)
        this.getCode(loginTmpCode)
      }
    }
    window.addEventListener('message', handler, false)
    this.$once('hook:beforeDestroy', () => {
      window.removeEventListener('message', handler)
    })
  }
}
</script>

<style lang="scss" module>
.container {
}
</style>
